package com.szh.cloud.role.service.impl;

import com.szh.cloud.mybatis.entity.PtRoleEntity;
import com.szh.cloud.mybatis.flexigrid.FlexResEntity;
import com.szh.cloud.mybatis.flexigrid.PagingBean;
import com.szh.cloud.mybatis.ztree.ZtreeEntity;
import com.szh.cloud.role.entity.SearchRoleEntity;
import com.szh.cloud.role.exception.RoleNameCcupdException;
import com.szh.cloud.role.repository.RoleDao;
import com.szh.cloud.role.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;

    @Override
    public FlexResEntity<PtRoleEntity> queryRoleListByPage(SearchRoleEntity entity, PagingBean paging) {
        FlexResEntity<PtRoleEntity> flexResEntity = new FlexResEntity<>();
        paging.deal(PtRoleEntity.class);
        entity.deal();
        flexResEntity.setPage(paging.getPage());
        List<PtRoleEntity> roleEntityList = roleDao.queryRoleListByPage(entity,paging);
        flexResEntity.setRawRecords(roleEntityList);

        Integer total = roleDao.queryRoleListTotal(entity);
        flexResEntity.setTotal(total);

        flexResEntity.deal();
        return flexResEntity;
    }

    @Override
    public List<ZtreeEntity> queryMenuByRoleId(String roleUuid) {
        List<ZtreeEntity> list = roleDao.queryMenuZtreeList();

        List<String> menuIdList = roleDao.queryMenuByRoleId(roleUuid);
        for(ZtreeEntity item:list){
            for(String menuId:menuIdList){
                if(menuId.equals(item.getId())){
                    item.setChecked(true);
                    break;
                }
            }
        }

        return list;
    }
    @Override
    public void saveMenuRefRole(String roleUuids, String menuIds) {
        String[] roleUuidArray = roleUuids.split(",");
        String[] menuIdArray = menuIds.split(",");
        for(String roleId:roleUuidArray){
            roleDao.deleteMenuByRole(roleId);
            if("".equals(menuIds)){
                continue;
            }
            for(String menuId:menuIdArray){
                roleDao.saveMenuRefRole(roleId,menuId);
            }
        }

    }
    @Override
    public void addRoleInfo(PtRoleEntity entity) {
        roleDao.addRoleInfo(entity);
    }

    @Override
    public void modifyRoleInfo(PtRoleEntity entity) {
        roleDao.modifyRoleInfo(entity);
    }
    @Override
    public void deleteRoleById(String roleUuids) throws RoleNameCcupdException {
        String[] roleUuidArray = roleUuids.split(",");
        List<String> menuIdList = roleDao.queryMenuListByRoleId(roleUuidArray);
        if(menuIdList.size() > 0 ){
            throw new RoleNameCcupdException("roleName occupy");
        }
        roleDao.deleteRoleById(roleUuidArray);
    }
}
